package org.zkoss.zktc.core.groovy

import org.zkoss.zktc.core.widget.WidgetDriver;

abstract class WidgetDriverScriptBase extends Script{

	
	public WidgetDriverScriptBase(){
		DynamicMethods.class;//init it
	}
	
	/* methods for assert*/
	def assertNotNull(){
		assertNotNull("widget should not be null",widget)
	}
	def assertNull(){
		assertNull("widget should be null",widget)
	}
	
	def attribute(String name){
		return widget?.getAttribute(name)
	}
	
	/* methods for widget*/

	
	def methodMissing(String name, args) {
		
		if(name.startsWith("assert")){
			if(name.startsWith("assertArray") && args){
				//workaround parameter of the assertArrayXXX of junit,
				def newargs = new ArrayList();
				args.each{
					if(it instanceof Collection){
						newargs.add(it.toArray());
					}else{
						newargs.add(it);
					}
				}
				args = newargs.toArray();
			}
			def fn = asserter?.metaClass?.getMetaMethod(name,args);
			if(fn) {
				fn.invoke(asserter,args)
				return 
			}
			throw new MissingMethodException(name, getClass(),args)
		}
		
		if(name.equals("find")){
			def fn = driver?.metaClass?.getMetaMethod("findWidget",args);
			if(fn) return widget = fn.invoke(driver,args);
		}
		if(name.equals("finds")){
			def fn = driver?.metaClass?.getMetaMethod("findWidgets",args);
			if(fn) return widgets = fn.invoke(driver,args);
		}
		if(name.equals("findElement")){
			def fn = driver?.metaClass?.getMetaMethod("findElement",args);
			if(fn) return fn.invoke(driver,args);
		}
		if(name.equals("findElements")){
			def fn = driver?.metaClass?.getMetaMethod("findElements",args);
			if(fn) return fn.invoke(driver,args);
		}
		
		
		def fn = driver?.metaClass?.getMetaMethod(name,args); 
		if(fn) return fn.invoke(driver,args);
		
		fn = widget?.metaClass?.getMetaMethod(name,args);
		if(fn) return fn.invoke(widget,args);

		throw new MissingMethodException(name, getClass(),args)
	}
	
//	def propertyMissing(String name) {
////		System.out.println(">>propertyMissing>>>>>>>>"+name);
//		def obj = null;
//		switch(name){
//		case "driver":
////			System.out.println(">>propertyMissing>>>>>>>>"+binding+">>"+binding.getVariables()+","+zktcContext);
//			return context?.getDriver();
//		}
//		if(obj!=null){
//			return obj;
//		}
//		throw new MissingPropertyException(name, getClass())
//	}
}